package com.api.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * json方法
 * 
 * @author Administrator
 *
 */
public class JsonHelp {

	/**
	 * 获取json中对应的value
	 * 
	 * @param json
	 * @param idkey
	 * @return
	 */
	public static String getJsonValue(String json, String idkey) {
		String result = "";
		JSONArray names = getJsonNames(json);
		if (names.contains(idkey)) {
			result = getJsonString(json, idkey);
		} else {
			for (int i = 0; i < names.size(); i++) {
				String key = (String) names.toArray()[i];
				String keyvalue = getJsonString(json, key);

				if (key.contains(idkey) || keyvalue.startsWith("{\"")) {
					return getJsonValue(keyvalue, idkey);
				} else {
				}
			}
		}

		return result;
	}

	public static String getJsonValue2(String json, String idkey) {
		String result = "";
		JSONArray names = getJsonNames(json);
		if (names.contains(idkey)) {
			result = getJsonString(json, idkey);
		} else {
			System.out.println("names.size():" + names.size());
			for (int i = 0; i < names.size(); i++) {
				String key = (String) names.toArray()[i];
				if (key.contains(idkey)) {
					String value = getJsonString(json, key);
					if (value.startsWith("{\"")) {
						JSONArray valueName = getJsonNames(value);
						String valueNameV = getJsonString(value, valueName.getString(0));
						System.out.println(valueNameV);
						return result = valueNameV;
					}
				} else {
					String value = getJsonString(json, key);
					return result = value;
				}
			}
		}

		return result;
	}

	/**
	 * 把json转换成对象，获取key值
	 * 
	 * @param str
	 * @return
	 */
	public static JSONArray getJsonNames(String str) {
		JSONObject js = JSONObject.fromObject(str);
		JSONArray names = js.names();
		return names;
	}

	/**
	 * 获取json中key对应的value
	 * 
	 * @param object
	 * @param key
	 * @return
	 */
	public static String getJsonString(Object object, String key) {
		String result = "";
		result = JSONObject.fromObject(object).getString(key);
		return result;
	}

}
